/**
 * Project Reactor
 */


#include "InetAddress.h"
#include <string.h>

/**
 * InetAddress implementation
 */


/**
 * @param port
 * @param ip
 */
InetAddress::InetAddress(unsigned short port, string & ip) {
    memset(&_addr, 0, sizeof(struct sockaddr_in));
    _addr.sin_addr.s_addr =  inet_addr(ip.c_str()); 
    _addr.sin_family = AF_INET;
    _addr.sin_port = htons(port);

}

InetAddress::InetAddress(unsigned short port)
{
    memset(&_addr, 0, sizeof(struct sockaddr_in));
    _addr.sin_addr.s_addr = INADDR_ANY;
    _addr.sin_family = AF_INET;
    _addr.sin_port = htons(port);

}
/**
 * @param addr
 */
InetAddress::InetAddress(const struct sockaddr_in & addr)
:_addr(addr)
{

}

/**
 * @return string
 */
string InetAddress::getip() const{
    char buff[INET_ADDRSTRLEN];//ipv4最大长度
    memset(buff, 0, sizeof(buff));
    if(inet_ntop(AF_INET, &_addr.sin_addr,buff,INET_ADDRSTRLEN) == nullptr)
        return "invaild address";
    return string(buff);
}

/**
 * @return unsigned_short
 */
unsigned short InetAddress::getport()const {
    return ntohs(_addr.sin_port);
}

/**
 * @return struct sockaddr_in *
 */
struct sockaddr_in * InetAddress::getInetAddressPtr() {
    return &_addr;
}
